package tgt

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	log "github.com/sirupsen/logrus"
	"strconv"
	"strings"
	"time"
)

func ManagerTgtService(c *gin.Context) {
	apiRequest := ManagerHostInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		sendErrorMessage(c, err, "", 5101)
		return
	}

	tgtMethod := apiRequest.Method
	hostAddress := apiRequest.HostAddress
	tgtName := apiRequest.GatewayName

	tgtList, err := queryGatewayListByFilter(hostAddress)
	if err != nil {
		sendErrorMessage(c, err, "", 5102)
		return
	}
	if tgtMethod == "install" {
		if len(tgtList) > 0 {
			err = fmt.Errorf("gateway %s is exist", hostAddress)
			sendErrorMessage(c, err, "", 5103)
			return
		}
	} else if tgtMethod == "uninstall" {
		log.Debug("uninstall gateway")
		//if len(tgtList) <= 0 {
		//	err = fmt.Errorf("gateway %s is not exist", hostAddress)
		//	sendErrorMessage(c, err, "", 5104)
		//	return
		//}
	} else {
		sendErrorMessage(c, fmt.Errorf("method %s is empty or error, must be install or uninstall, please check", tgtMethod), "", 5221)
		return

	}

	tgtIni := loadTgtIni()
	tgtIni.Section("tgt").Key("tgt1 ansible_ssh_host").SetValue(hostAddress)

	tgtIniStr, err := saveTgtiniToString(tgtIni)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}
	tgtYamlStr := loadTgtYaml()
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	//print(tgtIniStr)
	//print(tgtYamlStr)

	// 连接SSH
	sshInfo := getSSHInfo()

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5202)
		return
	}

	defer sshClient.Close()
	tgtIniFileName := "tgt-" + uuid.New().String() + ".ini"
	tgtYamlFileName := "deploy_tgt-" + uuid.New().String() + ".yml"
	errCode, err := scpConfigFile(sshClient, tgtIniStr, tgtYamlStr, tgtIniFileName, tgtYamlFileName)
	if err != nil {
		sendErrorMessage(c, err, "", errCode)
	}

	//tgtIniFileName := "tgt-" + uuid.New().String() + ".ini"
	//tgtYamlFileName := "deploy_tgt-" + uuid.New().String() + ".yml"
	//iniSource, err := sshClient.sftpClient.Create(ansible_dir + "/" + tgtIniFileName)
	//if err != nil {
	//	sendErrorMessage(c, fmt.Errorf("failed to open remote file: %s", err.Error()), 5211)
	//	return
	//}
	//if _, err := io.Copy(iniSource, bytes.NewBufferString(tgtIniStr)); err != nil {
	//	sendErrorMessage(c, fmt.Errorf("failed to write ini file: %s", err.Error()), 5212)
	//	return
	//}
	//yamlSource, err := sshClient.sftpClient.Create(ansible_dir + "/" + tgtYamlFileName)
	//if err != nil {
	//	sendErrorMessage(c, fmt.Errorf("failed to open remote file: %s", err.Error()), 5211)
	//	return
	//}
	//if _, err := io.Copy(yamlSource, bytes.NewBufferString(tgtYamlStr)); err != nil {
	//	sendErrorMessage(c, fmt.Errorf("failed to write ini file: %s", err.Error()), 5212)
	//	return
	//}

	execCommand := ""
	//sqlStr := ""
	if tgtMethod == "install" {
		execCommand = installCommand(tgtIniFileName, tgtYamlFileName)
	} else if tgtMethod == "uninstall" {
		execCommand = uninstallCommand(tgtIniFileName, tgtYamlFileName)
	}
	if execCommand == "" {
		sendErrorMessage(c, fmt.Errorf("method %s is empty or error, must be install or uninstall, please check", tgtMethod), "", 5221)
		return
	}
	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to %s tgt on Host: %s Error: %s", tgtMethod, hostAddress, err.Error()), string(buf), 5222)
		return
	}
	execResult, err := getAnsibleResult(string(buf))
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get ansible result: %s Error: %s", hostAddress, err.Error()), string(buf), 5223)
		return
	}
	if tgtMethod == "install" {
		insertID, err := insertGatewayData(GatewayInfo{
			Name:       tgtName,
			Host:       hostAddress,
			CreateTime: time.Now(),
			Active:     1,
		})
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("insert success, last id:[%d]\n", insertID)
	} else if tgtMethod == "uninstall" {
		affectRows, err := deleteGatewayData(hostAddress)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete gateway success, affected rows:[%d]\n", affectRows)
		//affectRows, err = deleteTargetData(hostAddress, "")
		//if err != nil {
		//	log.Errorf("datebase error: %s", err.Error())
		//}
		//log.Infof("delete target success, affected rows:[%d]\n", affectRows)
	}

	sendSuccessMessage(c, fmt.Sprintf("%s tgt on %s succeed", tgtMethod, hostAddress), string(buf), execResult)

	//successResponse := SuccessResponse{
	//	SuccessMessage: fmt.Sprintf("Install tgt on %s succeed", hostAddress),
	//	Code:           200,
	//	RawMessage:     string(buf),
	//}
	//c.JSON(200, successResponse)
	return
}

func ShowTgtStatus(c *gin.Context) {
	apiRequest := HostInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		sendErrorMessage(c, err, "", 5101)
		return
	}

	hostAddress := apiRequest.Address

	// 连接SSH
	sshInfo := getSSHInfo()
	sshInfo.HostAddress = hostAddress + ":22"

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	defer sshClient.Close()

	execCommand := showTgtStatusCommand()
	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get tgt status on Host: %s Error: %s", hostAddress, err.Error()), string(buf), 5222)
		return
	}
	gwInfo, _ := queryGatewayInfo(hostAddress)
	// 匹配运行状态
	activeState, subState, errorMsg := getTgtStatus(string(buf))
	if activeState == "active" && subState == "running" {
		affectRows, err := updateGatewayInfo(hostAddress, 1)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete success, affected rows:[%d]\n", affectRows)
		sendSuccessMessage(c, fmt.Sprintf("Host=%s|ActiveState=%s|SubState=%s|Services=%s|Error=%s", hostAddress, activeState, subState, "tgt.service", "none"), string(buf), AnsibleResult{-1, -1, -1, -1})
		//successResponse := SuccessResponse{
		//	SuccessMessage: fmt.Sprintf("Host=%s|ActiveState=%s|SubState=%s|Services=%s|Error=%s", hostAddress, activeState, subState, "tgt.service", "none"),
		//	Code:           200,
		//	RawMessage:     string(buf),
		//}
		//c.JSON(200, successResponse)
		return
	} else {
		if strings.Contains(errorMsg, "not found") {
			if gwInfo.Host == hostAddress {
				affectRows, err := deleteGatewayData(hostAddress)
				if err != nil {
					log.Errorf("datebase error: %s", err.Error())
				}
				log.Infof("delete success, affected rows:[%d]\n", affectRows)
			}
			errMessage := fmt.Errorf("Host=%s|ActiveState=%s|SubState=%s|Services=%s|Error=%s", hostAddress, activeState, subState, "none", errorMsg)
			sendErrorMessage(c, errMessage, "", 5300)
			return
		} else {
			affectRows, err := updateGatewayInfo(hostAddress, 0)
			if err != nil {
				log.Errorf("datebase error: %s", err.Error())
			}
			log.Infof("delete success, affected rows:[%d]\n", affectRows)
			errMessage := fmt.Errorf("Host=%s|ActiveState=%s|SubState=%s|Services=%s|Error=%s", hostAddress, activeState, subState, "tgt.service", errorMsg)
			sendErrorMessage(c, errMessage, "", 5300)
			return
		}
	}
}

func GetTgtList(c *gin.Context) {
	tgtList, err := queryGatewayList()
	if err != nil {
		log.Errorf("GetTgtList: get tgt list error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	tgtListStr, err := json.Marshal(tgtList)
	if err != nil {
		log.Errorf("GetTgtList: parse list to json error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	if len(tgtList) <= 0 {
		log.Errorf("GetTgtList: no tgt in tgtlist")
		sendErrorMessage(c, err, string(tgtListStr), 5501)
		return
	}

	sendSuccessMessage(c, "get tgtlist succeed", string(tgtListStr), AnsibleResult{-1, -1, -1, -1})
	return

	//if
}

// ManagerTarget 创建/删除 Target
func ManagerTarget(c *gin.Context) {
	apiRequest := TargetInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("AddTarget: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	targetMethod := apiRequest.TargetMethod
	targetHostAddress := apiRequest.HostAddress
	targetID := apiRequest.TargetID

	targetList, err := queryTargetListByFilter(targetHostAddress, targetID)
	if err != nil {
		sendErrorMessage(c, err, "", 5102)
		return
	}
	if targetMethod == "add" {
		if len(targetList) > 0 {
			err = fmt.Errorf("gateway %s, target id %s is exist", targetHostAddress, targetID)
			sendErrorMessage(c, err, "", 5106)
			return
		}
	} else if targetMethod == "remove" {
		log.Debug("remove target")
		//if len(targetList) <= 0 {
		//	err = fmt.Errorf("gateway %s, target id %s is not exist", targetHostAddress, targetID)
		//	sendErrorMessage(c, err, "", 5107)
		//	return
		//}
	} else {
		sendErrorMessage(c, fmt.Errorf("method %s is empty or error, must be add or remove, please check", targetMethod), "", 5221)
		return
	}

	// 根据前端的数据生成ini文件
	tgtIni := loadTgtIni()
	tgtIni.Section("tgt").Key("tgt1 ansible_ssh_host").SetValue(targetHostAddress)
	tgtIni.Section("tgt:vars").Key("tgt_tidid").SetValue(targetID)

	tgtIniStr, err := saveTgtiniToString(tgtIni)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}
	tgtYamlStr := loadTgtYaml()
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	// 连接SSH
	sshInfo := getSSHInfo()

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5202)
		return
	}

	defer sshClient.Close()
	tgtIniFileName := "tgt-target-" + uuid.New().String() + ".ini"
	tgtYamlFileName := "deploy_tgt-target-" + uuid.New().String() + ".yml"
	errCode, err := scpConfigFile(sshClient, tgtIniStr, tgtYamlStr, tgtIniFileName, tgtYamlFileName)
	if err != nil {
		sendErrorMessage(c, err, "", errCode)
	}

	execCommand := ""
	if targetMethod == "add" {
		execCommand = addTargetCommand(tgtIniFileName, tgtYamlFileName)
	} else if targetMethod == "remove" {
		execCommand = removeTargetCommand(tgtIniFileName, tgtYamlFileName)
	}

	if execCommand == "" {
		sendErrorMessage(c, fmt.Errorf("method %s is empty or error, must be add or remove, please check", targetMethod), "", 5221)
		return
	}

	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to %s tgt on Host: %s, target id: %s, Error: %s", targetMethod, targetHostAddress, targetID, err.Error()), string(buf), 5222)
		return
	}
	execResult, err := getAnsibleResult(string(buf))
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get ansible result: %s, target id: %s, Error: %s", targetHostAddress, targetID, err.Error()), "", 5223)
		return
	}
	if targetMethod == "add" {
		targetIDInt, _ := strconv.Atoi(targetID)
		insertID, err := insertTargetData(TargetDBInfo{
			Host:       targetHostAddress,
			CreateTime: time.Now(),
			TargetID:   targetIDInt,
		})
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("insert success, last id:[%d]\n", insertID)
	} else if targetMethod == "remove" {
		affectRows, err := deleteTargetData(targetHostAddress, targetID)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete target success, affected rows:[%d]\n", affectRows)
		affectRows, err = deleteLUNData(targetHostAddress, targetID)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete lun success, affected rows:[%d]\n", affectRows)
		affectRows, err = deleteTargetIPData(targetHostAddress, targetID)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete bind ip success, affected rows:[%d]\n", affectRows)
		affectRows, err = deleteTargetUserData(targetHostAddress, targetID)
		if err != nil {
			log.Errorf("datebase error: %s", err.Error())
		}
		log.Infof("delete bind user success, affected rows:[%d]\n", affectRows)
	}

	sendSuccessMessage(c, fmt.Sprintf("%s tgt on %s succeed, taget id %s", targetMethod, targetHostAddress, targetID), string(buf), execResult)
	//successResponse := SuccessResponse{
	//	SuccessMessage: fmt.Sprintf("Install tgt on %s succeed, taget id %s", targetHostAddress, targetID),
	//	Code:           200,
	//	RawMessage:     string(buf),
	//}
	//c.JSON(200, successResponse)
	return
}

func GetTargetList(c *gin.Context) {
	apiRequest := QueryTargetRequest{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("GetTargetList: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	queryHost := apiRequest.Host
	targetList, err := queryTargetList(queryHost)

	if err != nil {
		log.Errorf("GetTargetList: get tgt list error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	targetListStr, err := json.Marshal(targetList)
	if err != nil {
		log.Errorf("GetTargetList: parse list to json error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	if len(targetList) <= 0 {
		log.Errorf("GetTargetList: no tgt in targetlist")
		sendErrorMessage(c, err, string(targetListStr), 5501)
		return
	}

	sendSuccessMessage(c, "get targetlist succeed", string(targetListStr), AnsibleResult{-1, -1, -1, -1})
	return

}

// AddLUN 创建LUN
func AddLUN(c *gin.Context) {
	apiRequest := LUNInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("AddLUN: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	lunHostAddress := apiRequest.HostAddress
	lunTargetID := apiRequest.TargetID
	lunID := apiRequest.LunID
	lunLogincalID := apiRequest.LogicalID
	lunSize := apiRequest.LunSize

	lunList, err := queryTargetLUNListByFilter(lunHostAddress, lunTargetID, lunID)
	if err != nil {
		sendErrorMessage(c, err, "", 5102)
		return
	}
	if len(lunList) > 0 {
		err = fmt.Errorf("host %s, target id %s, lun id %s is exist", lunHostAddress, lunTargetID, lunID)
		sendErrorMessage(c, err, "", 5108)
		return
	}

	// 根据前端的数据生成ini文件
	tgtIni := loadTgtIni()
	tgtIni.Section("tgt").Key("tgt1 ansible_ssh_host").SetValue(lunHostAddress)
	tgtIni.Section("tgt:vars").Key("tgt_tidid").SetValue(lunTargetID)
	tgtIni.Section("tgt:vars").Key("tgt_lunid").SetValue(lunID)
	tgtIni.Section("tgt:vars").Key("logical_id").SetValue(lunLogincalID)
	tgtIni.Section("tgt:vars").Key("lun_size").SetValue(lunSize)

	tgtIniStr, err := saveTgtiniToString(tgtIni)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}
	tgtYamlStr := loadTgtYaml()
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	// 连接SSH
	sshInfo := getSSHInfo()

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5202)
		return
	}

	defer sshClient.Close()
	tgtIniFileName := "tgt-lun-" + uuid.New().String() + ".ini"
	tgtYamlFileName := "deploy_tgt-lun-" + uuid.New().String() + ".yml"
	errCode, err := scpConfigFile(sshClient, tgtIniStr, tgtYamlStr, tgtIniFileName, tgtYamlFileName)
	if err != nil {
		sendErrorMessage(c, err, "", errCode)
	}

	execCommand := addLUNCommand(tgtIniFileName, tgtYamlFileName)

	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to add lun on Host: %s, target id: %s, lun id: %s, logical id: %s, lun size: %s, Error: %s", lunHostAddress, lunTargetID, lunID, lunLogincalID, lunSize, err.Error()), string(buf), 5222)
		return
	}
	execResult, err := getAnsibleResult(string(buf))
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get ansible result: %s, target id: %s, lun id: %s, logical id: %s, lun size: %s, Error: %s", lunHostAddress, lunTargetID, lunID, lunLogincalID, lunSize, err.Error()), string(buf), 5223)
		return
	}
	targetIDInt, _ := strconv.Atoi(lunTargetID)
	lunIDInt, _ := strconv.Atoi(lunID)
	lunLogincalIDInt, _ := strconv.Atoi(lunLogincalID)
	lunSizeInt, _ := strconv.Atoi(lunSize)
	insertID, err := insertLUNData(LUNDBInfo{
		Host:       lunHostAddress,
		TargetID:   targetIDInt,
		LunID:      lunIDInt,
		LogicalID:  lunLogincalIDInt,
		LunSize:    lunSizeInt,
		CreateTime: time.Now(),
	})
	if err != nil {
		log.Errorf("datebase error: %s", err.Error())
	}
	log.Infof("insert success, last id:[%d]\n", insertID)

	sendSuccessMessage(c, fmt.Sprintf("add lun on %s succeed, taget id %s, lun id: %s, logical id: %s, lun size: %s", lunHostAddress, lunTargetID, lunID, lunLogincalID, lunSize), string(buf), execResult)
	//successResponse := SuccessResponse{
	//	SuccessMessage: fmt.Sprintf("Install tgt on %s succeed, taget id %s", targetHostAddress, targetID),
	//	Code:           200,
	//	RawMessage:     string(buf),
	//}
	//c.JSON(200, successResponse)
	return
}

func GetTargetLUNList(c *gin.Context) {
	apiRequest := QueryTargetInfoRequest{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("GetTargetLUNList: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	queryHost := apiRequest.Host
	queryTargetID := apiRequest.TargetID
	targetLUNList, err := queryTargetLUNList(queryHost, queryTargetID)

	if err != nil {
		log.Errorf("GetTargetLUNList: get target lun list error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	targetListStr, err := json.Marshal(targetLUNList)
	if err != nil {
		log.Errorf("GetTargetLUNList: parse list to json error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	if len(targetLUNList) <= 0 {
		log.Errorf("GetTargetLUNList: no target lun in targetlunlist")
		sendErrorMessage(c, err, string(targetListStr), 5501)
		return
	}

	sendSuccessMessage(c, "get targetlun list succeed", string(targetListStr), AnsibleResult{-1, -1, -1, -1})
	return

}

// BindTargetIP Target绑定IP
func BindTargetIP(c *gin.Context) {
	apiRequest := TargetIPInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("AddLUN: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	targetAddress := apiRequest.HostAddress
	targetID := apiRequest.TargetID
	targetBindIP := apiRequest.IPAddress

	ipList, err := queryTargetIPListByFilter(targetAddress, targetID, targetBindIP)
	if err != nil {
		sendErrorMessage(c, err, "", 5102)
		return
	}
	if len(ipList) > 0 {
		err = fmt.Errorf("host %s, target id %s, ip %s is exist", targetAddress, targetID, targetBindIP)
		sendErrorMessage(c, err, "", 5109)
		return
	}

	// 根据前端的数据生成ini文件
	tgtIni := loadTgtIni()
	tgtIni.Section("tgt").Key("tgt1 ansible_ssh_host").SetValue(targetAddress)
	tgtIni.Section("tgt:vars").Key("tgt_tidid").SetValue(targetID)
	tgtIni.Section("tgt:vars").Key("tgt_allow_ip").SetValue(targetBindIP)

	tgtIniStr, err := saveTgtiniToString(tgtIni)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}
	tgtYamlStr := loadTgtYaml()
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	// 连接SSH
	sshInfo := getSSHInfo()

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5202)
		return
	}

	defer sshClient.Close()
	tgtIniFileName := "tgt-ip-" + uuid.New().String() + ".ini"
	tgtYamlFileName := "deploy_tgt-ip-" + uuid.New().String() + ".yml"
	errCode, err := scpConfigFile(sshClient, tgtIniStr, tgtYamlStr, tgtIniFileName, tgtYamlFileName)
	if err != nil {
		sendErrorMessage(c, err, "", errCode)
	}

	execCommand := bindIPCommand(tgtIniFileName, tgtYamlFileName)

	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to bind ip on Host: %s, target id: %s, ip address: %s, Error: %s", targetAddress, targetID, targetBindIP, err.Error()), string(buf), 5222)
		return
	}
	execResult, err := getAnsibleResult(string(buf))
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get ansible result: %s, target id: %s, ip address: %s, Error: %s", targetAddress, targetID, targetBindIP, err.Error()), string(buf), 5223)
		return
	}
	targetIDInt, _ := strconv.Atoi(targetID)
	insertID, err := insertTargetIPData(TargetIPDBInfo{
		Host:       targetAddress,
		TargetID:   targetIDInt,
		IPAddress:  targetBindIP,
		CreateTime: time.Now(),
	})
	if err != nil {
		log.Errorf("datebase error: %s", err.Error())
	}
	log.Infof("insert success, last id:[%d]\n", insertID)

	sendSuccessMessage(c, fmt.Sprintf("bind ip on %s succeed, taget id %s, ip address: %s", targetAddress, targetID, targetBindIP), string(buf), execResult)
	//successResponse := SuccessResponse{
	//	SuccessMessage: fmt.Sprintf("Install tgt on %s succeed, taget id %s", targetHostAddress, targetID),
	//	Code:           200,
	//	RawMessage:     string(buf),
	//}
	//c.JSON(200, successResponse)
	return
}

func GetTargetIPList(c *gin.Context) {
	apiRequest := QueryTargetInfoRequest{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("GetTargetIPList: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	queryHost := apiRequest.Host
	queryTargetID := apiRequest.TargetID
	targetIPList, err := queryTargetIPList(queryHost, queryTargetID)

	if err != nil {
		log.Errorf("GetTargetIPList: get target bind ip list error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	targetListStr, err := json.Marshal(targetIPList)
	if err != nil {
		log.Errorf("GetTargetIPList: parse list to json error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	if len(targetIPList) <= 0 {
		log.Errorf("GetTargetIPList: no target bind ip in targetiplist")
		sendErrorMessage(c, err, string(targetListStr), 5501)
		return
	}

	sendSuccessMessage(c, "get target bind ip list succeed", string(targetListStr), AnsibleResult{-1, -1, -1, -1})
	return

}

// BindTargetUser Target绑定User
func BindTargetUser(c *gin.Context) {
	apiRequest := TargetUserInfo{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("BindTargetUser: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	targetAddress := apiRequest.HostAddress
	targetID := apiRequest.TargetID
	targetUsername := apiRequest.Username
	targetPassword := apiRequest.Password

	userList, err := queryTargetUserListByFilter(targetAddress, targetID, targetUsername)
	if err != nil {
		sendErrorMessage(c, err, "", 5102)
		return
	}
	if len(userList) > 0 {
		err = fmt.Errorf("host %s, target id %s, user %s is exist", targetAddress, targetID, targetUsername)
		sendErrorMessage(c, err, "", 5110)
		return
	}

	// 根据前端的数据生成ini文件
	tgtIni := loadTgtIni()
	tgtIni.Section("tgt").Key("tgt1 ansible_ssh_host").SetValue(targetAddress)
	tgtIni.Section("tgt:vars").Key("tgt_tidid").SetValue(targetID)
	tgtIni.Section("tgt:vars").Key("target_username").SetValue(targetUsername)
	tgtIni.Section("tgt:vars").Key("target_passwd").SetValue(targetPassword)

	tgtIniStr, err := saveTgtiniToString(tgtIni)
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}
	tgtYamlStr := loadTgtYaml()
	if err != nil {
		sendErrorMessage(c, err, "", 5201)
		return
	}

	// 连接SSH
	sshInfo := getSSHInfo()

	sshClient, err := connectSSHClient(sshInfo)
	if err != nil {
		sendErrorMessage(c, err, "", 5202)
		return
	}

	defer sshClient.Close()
	tgtIniFileName := "tgt-user-" + uuid.New().String() + ".ini"
	tgtYamlFileName := "deploy_tgt-user-" + uuid.New().String() + ".yml"
	errCode, err := scpConfigFile(sshClient, tgtIniStr, tgtYamlStr, tgtIniFileName, tgtYamlFileName)
	if err != nil {
		sendErrorMessage(c, err, "", errCode)
	}

	execCommand := bindUserCommand(tgtIniFileName, tgtYamlFileName)

	log.Info(execCommand)
	buf, err := sshClient.Session.CombinedOutput(execCommand)
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to bind user on Host: %s, target id: %s, username: %s, password: %s, Error: %s", targetAddress, targetID, targetUsername, targetPassword, err.Error()), string(buf), 5222)
		return
	}
	execResult, err := getAnsibleResult(string(buf))
	if err != nil {
		sendErrorMessage(c, fmt.Errorf("failed to get ansible result: %s, target id: %s, username: %s, password: %s, Error: %s", targetAddress, targetID, targetUsername, targetPassword, err.Error()), string(buf), 5223)
		return
	}
	targetIDInt, _ := strconv.Atoi(targetID)
	insertID, err := insertTargetUserData(TargetUserDBInfo{
		Host:       targetAddress,
		TargetID:   targetIDInt,
		Username:   targetUsername,
		Password:   targetPassword,
		CreateTime: time.Now(),
	})
	if err != nil {
		log.Errorf("datebase error: %s", err.Error())
	}
	log.Infof("insert success, last id:[%d]\n", insertID)

	sendSuccessMessage(c, fmt.Sprintf("bind ip on %s succeed, taget id %s, username: %s, password: %s", targetAddress, targetID, targetUsername, targetPassword), string(buf), execResult)
	//successResponse := SuccessResponse{
	//	SuccessMessage: fmt.Sprintf("Install tgt on %s succeed, taget id %s", targetHostAddress, targetID),
	//	Code:           200,
	//	RawMessage:     string(buf),
	//}
	//c.JSON(200, successResponse)
	return
}

func GetTargetUserList(c *gin.Context) {
	apiRequest := QueryTargetInfoRequest{}
	err := c.ShouldBind(&apiRequest)
	if err != nil {
		log.Errorf("GetTargetUserList: Get request args error: %s", err.Error())
		sendErrorMessage(c, err, "", 5101)
		return
	}
	queryHost := apiRequest.Host
	queryTargetID := apiRequest.TargetID
	targetUserList, err := queryTargetUserList(queryHost, queryTargetID)

	if err != nil {
		log.Errorf("GetTargetUserList: get target bind user list error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	targetListStr, err := json.Marshal(targetUserList)
	if err != nil {
		log.Errorf("GetTargetUserList: parse list to json error: %s", err.Error())
		sendErrorMessage(c, err, "", 5500)
		return
	}
	if len(targetUserList) <= 0 {
		log.Errorf("GetTargetUserList: no target bind user in targetiplist")
		sendErrorMessage(c, err, string(targetListStr), 5501)
		return
	}

	sendSuccessMessage(c, "get target bind user list succeed", string(targetListStr), AnsibleResult{-1, -1, -1, -1})
	return

}

func TestDB(c *gin.Context) {
	info, err := queryGatewayInfo("192.168.0.104")
	if err != nil {
		sendErrorMessage(c, err, "", 5700)
	}
	fmt.Println(info)
	//dbClient := db.DBClient{}
	//dbClient.InitDBInfo("root", "wfdz@admin2022", "192.168.0.101:32306", "vmservice")
	//err := dbClient.InitDB()
	//if err != nil {
	//	sendErrorMessage(c, err, 5700)
	//}
	//affectRows, err := dbClient.CreateDatabase()
	//if err != nil {
	//	sendErrorMessage(c, err, 5700)
	//}
	//if affectRows == 1 {
	//}
	//isExist, err := dbClient.CheckoutDatabase()
	//if err != nil {
	//	sendErrorMessage(c, err, 300)
	//}
	//if isExist == true {
	//
	//}
	c.JSON(200, nil)
}

func sendErrorMessage(c *gin.Context, err error, rawMsg string, code int) {
	errResponse := ErrorResponse{
		MessageType:  "error",
		ErrorMessage: err.Error(),
		RawMessage:   rawMsg,
		Code:         code,
	}
	c.JSON(400, errResponse)
	return
}

func sendSuccessMessage(c *gin.Context, successMsg, rawMsg string, result AnsibleResult) {
	successResponse := SuccessResponse{
		MessageType:    "success",
		SuccessMessage: successMsg,
		Code:           200,
		RawMessage:     rawMsg,
		AnsibleResult:  result,
	}
	c.JSON(200, successResponse)
	return
}
